package cn.haohaowo.entity;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import cn.haohaowo.service.BookBizService;
import cn.haohaowo.service.impl.BookBizServiceImpl;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class ShoppingCart implements Serializable {

	private static final long serialVersionUID = 8716301707851139388L;
	
	private List<CartItem> cartItems = new ArrayList<CartItem>();
	
	public void addBook(Book book){
		this.addBook(book, 1);
	}
	
	public void addBook(Book book, int quantity){
		if(null != book){
			int bookId = book.getId();
			CartItem item = getCartItem(bookId);
			if(null == item){
				item = new CartItem(book, quantity);
				cartItems.add(item);
			}else{
				item.setQuantity(item.getQuantity() + quantity);
			}
		}
	}
	
	public CartItem getCartItem(Integer bookid){
		for (CartItem item : cartItems) {
			if(item.getBoookid().equals(bookid)){
				return item;
			}
		}
		return null;
	}
	
	public void updateQuantity(Book book, int quantity){
		CartItem item = getCartItem(book.getId());
		if(null != item){
			item.setQuantity(quantity);
		}
	}
	
	public Integer getTotalPrice(){
		int totalprice = 0;
		for (CartItem item : cartItems) {
			totalprice += item.getTotalPrice();
		}
		return totalprice;
	}
	
	public Integer getTotalOrgiPrice(){
		int totalOrgiPrice = 0;
		for(CartItem item : cartItems){
			totalOrgiPrice += item.getTotalOrgiPrice();
		}
		return totalOrgiPrice;
	}
	
	public Integer getTotalSaved() {
		return getTotalOrgiPrice() - getTotalPrice();
	}
	
	public void removeBook(Integer bookid){
		CartItem item = getCartItem(bookid);
		if(null != item){
			cartItems.remove(item);
		}
	}
	
	public int getSize(){
		return cartItems.size();
	}
	
	public void clear(){
		cartItems.clear();
	}
	
	public boolean isEmpty(){
		return null == cartItems || cartItems.size() == 0;
	}
	
	public List<OrderDetail> createOrderDetailFromCartItem(){
		List<OrderDetail> details = new ArrayList<OrderDetail>(cartItems.size());
		for(CartItem item : cartItems){
			OrderDetail od = item.createOrderDetail();
			details.add(od);
		}
		return details;
	}

	public List<CartItem> getCartItems() {
		return cartItems;
	}
	
}
 